﻿using System;
using System.Web.Mvc;
using Castle.MicroKernel;

namespace FoodBank.Web
{
    /// <summary>
    /// Controller factory that returns controller classes provided by Castle Windsor IoC
    /// </summary>
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel _kernel;

        /// <summary>
        /// Initializes a new instance of the <see cref="WindsorControllerFactory"/> class.
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        public WindsorControllerFactory(IKernel kernel)
        {
            _kernel = kernel;
        }

        /// <summary>
        /// Releases the specified controller.
        /// </summary>
        /// <param name="controller">The controller to release.</param>
        public override void ReleaseController(IController controller)
        {
           _kernel.ReleaseComponent(controller);
        }

        /// <summary>
        /// Creates the specified controller by using the specified request context.
        /// </summary>
        /// <param name="requestContext">The context of the HTTP request, which includes the HTTP context and route data.</param>
        /// <param name="controllerName">The name of the controller.</param>
        /// <returns>A reference to the controller.</returns>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestContext"/> parameter is null.</exception>
        /// <exception cref="T:System.ArgumentException">The <paramref name="controllerName"/> parameter is null or empty.</exception>
        public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            var controllerComponentName = controllerName + "Controller";

            try
            {
                return _kernel.Resolve<IController>(controllerComponentName);
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}